package com.ja.openchat.ui.found;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.BR;
import com.google.gson.JsonObject;
import com.ja.openchat.R;
import com.ja.openchat.adapters.CircleMessageAdapter;
import com.ja.openchat.ui.base.JaBaseActivity;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.circle.BlogInfo;
import com.zy.openchat.core.model.circle.BlogUnreadsInfo;
import com.zy.openchat.core.model.file.FileInfo;
import com.zy.openchat.core.model.file.FileTaskInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.Common;

import java.util.Map;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class CircleMessageActivity extends JaBaseActivity {
    @BindView(R.id.tv_ok_right)
    TextView tv_ok_right;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;

    public static void start(Context context) {
        Intent intent = new Intent(context, CircleMessageActivity.class);
        context.startActivity(intent);
    }

    private CircleMessageAdapter mAdapter;

    @Override
    protected boolean isHaveButterKnife() {
        return true;
    }

    @Override
    public void initData() {
        setTitle(getString(R.string.comment_message));
        tv_ok_right.setVisibility(View.GONE);
        tv_ok_right.setBackground(ContextCompat.getDrawable(this, R.drawable.transparent_shape));
        tv_ok_right.setTextColor(ContextCompat.getColor(this, R.color.nav_btn_bg));
        tv_ok_right.setText(getString(R.string.empty_text));
        tv_ok_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showProgress();
                TelegramManager.getTelegramManager().clearBlogMessages(CircleMessageActivity.this, new TgResultBlock<TgResponse>() {
                    @Override
                    public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                        hideProgress();
                        if (obj.ok) {
                            currentPage = 1;
                            requestReplyInfo(currentPage);
                        } else {
                            ToastUtils.showShort(obj == null ? getString(R.string.request_error) : obj.errString);
                        }
                    }

                    @Override
                    public void onTimeout(Map<String, Object> request) {
                        hideProgress();
                        ToastUtils.showShort(getString(R.string.request_error));
                    }
                });
            }
        });
        mAdapter = new CircleMessageAdapter();
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.setAdapter(mAdapter);
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
        mAdapter.setEmptyView(R.layout.status_center_empty_view);
        requestReplyInfo(currentPage);

    }

    private int currentPage = 1;

    private void requestReplyInfo(int page) {
        TelegramManager.getTelegramManager().getBlogUnreads(this, 20, (page - 1) * 20, new TgResultBlock<BlogUnreadsInfo>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, BlogUnreadsInfo obj) {
                if (obj == null || Common.isEmpty(obj.messages)) {
                    if (page == 1) {
                        mAdapter.setNewInstance(null);
                        tv_ok_right.setVisibility(View.GONE);
                    }
                } else {
                    if (page == 1) {
                        if (page == 1) {
                            tv_ok_right.setVisibility(View.VISIBLE);
                        }
                        mAdapter.setNewInstance(obj.messages);
                    } else {
                        mAdapter.addData(obj.messages);
                    }
                }

                mAdapter.getLoadMoreModule().loadMoreEnd(true);
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                mAdapter.getLoadMoreModule().loadMoreEnd(true);
            }
        });
    }

    @Override
    protected boolean isHaveEventBus() {
        return true;
    }

    @Override
    public void onTgEvent(TgEvent tg_event) {
        if (tg_event == null) {
            return;
        }
        try {
            switch (tg_event.event) {
                case EUser_Td_Contact_Photo_Ok:
                case EUser_Td_UpdateContactInfo:
                    if ((tg_event.data instanceof UserInfo)) {
                        UserInfo userInfo = (UserInfo) tg_event.data;
                        Observable.create(new ObservableOnSubscribe<DiffUtil.DiffResult>() {
                            @Override
                            public void subscribe(ObservableEmitter<DiffUtil.DiffResult> e) {
                                DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new BlogMessageAvatarDiffCallBack(mAdapter.getData(), mAdapter.getData()), false);
                                e.onNext(diffResult);
                            }
                        }).subscribeOn(Schedulers.computation())
                                .observeOn(AndroidSchedulers.mainThread())
                                .subscribe(new Consumer<DiffUtil.DiffResult>() {
                                    @Override
                                    public void accept(DiffUtil.DiffResult diffResult) {
                                        diffResult.dispatchUpdatesTo(mAdapter);
                                    }
                                });
                    }
                    break;
                case EUser_Td_Message_Photo_Ok:
                case EUser_Td_Message_Video_Ok:
                    if (tg_event.data instanceof FileTaskInfo && tg_event.dataEx instanceof FileInfo) {
                        FileInfo fileInfo = (FileInfo) tg_event.dataEx;
                        String ids = ((FileTaskInfo) tg_event.data).id;
                        if (!TextUtils.isEmpty(ids) && ids.contains("_")) {
                            String[] idArray = ids.split("_");
                            if (idArray.length > 1) {
                                BlogInfo blogInfo = mAdapter.requestBlogInfo(Long.parseLong(idArray[1]));
                                if (blogInfo != null) {
                                    switch (tg_event.event) {
                                        case EUser_Td_Message_Photo_Ok:
                                            blogInfo.updatePhotoFile(fileInfo);
                                            break;
                                        case EUser_Td_Message_Video_Ok:
                                            blogInfo.updateVideoFile(fileInfo);
                                            break;
                                    }
                                    mAdapter.updateBlogInfo(blogInfo);
                                }
                            }
                        }
                    }
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_circle_reply;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }
}
